package li.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import li.dao.*;
import li.dto.*;
import li.service.CartService;
import li.service.OrderService;
import li.util.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    CartService cs;
    @Autowired
    OrderMapper om;

    @Autowired
    AmountMapper am;

    @Autowired
    OrderDetailMapper detailMapper;

    @Autowired
    CreditMapper creditMapper;

    @Autowired
    PayMapper pm;

    @Transactional
    @Override
    public String createOrder(Porder order, TbUser user) {
        //1.产生订单
        Cart cart = cs.findCart(user);
        order.setTotalprice(cart.getTotalPrice());
        order.setConsumerId(user.getId());
        om.insert(order);

        //2.添加订单明细
        List<CartItem> items = cart.getItems();
        Orderdetail ot = null;
        for (CartItem item : items) {
            ot = new Orderdetail()
                    .setSkuId(item.getPid())
                    .setPrice(item.getPrice())
                    .setScount(item.getPcount())
                    .setSkuName(item.getPname())
                    .setOrderId(order.getId())
                    .setSumprice(item.getSumprice());
            detailMapper.insert(ot);
        }

        //3.修改信用额度
        QueryWrapper q = new QueryWrapper();
        q.eq("account",user.getAccount());
        TbAmount amount = am.selectOne(q);
        if(amount==null){
            amount = new TbAmount();
            amount.setAccount(user.getAccount());
            am.insert(amount);
        }
        amount.setUseamount(amount.getUseamount()+order.getTotalprice());
        amount.setFreeamount(amount.getFreeamount()-order.getTotalprice());
        if(amount.getFreeamount() < 0){
            throw new RuntimeException("你的可用额度不够");
        }
        am.updateById(amount);

        //4.生成帐单
        Credit cre = new Credit();
        cre.setPeriod(order.getStage());
        cre.setOrderId(order.getId());
        cre.setConsumerId(order.getConsumerId());
        cre.setAmount(order.getTotalprice()+0.3*order.getTotalprice()*order.getStage()/12);
        creditMapper.insert(cre);

        //5.生成还款计划
        Calendar c = Calendar.getInstance();
        Payback pay ;
        for (int i = 0; i < cre.getPeriod(); i++) {
            pay = new Payback();
            pay.setCreditId(cre.getId());
            pay.setAmount(cre.getAmount()/cre.getPeriod());
            c.add(Calendar.MONTH,1);
            pay.setExpectpaytime(c.getTime());
            pm.insert(pay);
        }

        Cache.CART.remove(order.getConsumerId());
        return "成功下订单";
    }
}
